package com.evan.petiymanta;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

import androidx.core.splashscreen.SplashScreen;

import com.evan.petiymanta.base.BaseActivity;
import com.evan.petiymanta.databinding.ActivitySplashBinding;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends BaseActivity {
    private static final String PREFS_NAME = "app_settings";
    private static final String KEY_DISCLAIMER_AGREED = "disclaimer_agreed";
    private ActivitySplashBinding binding;
    private boolean isDisclaimerShowing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SplashScreen.installSplashScreen(this);
        super.onCreate(savedInstanceState);
        binding = ActivitySplashBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setupWindowInsets();

        // 检查是否已同意免责声明
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean hasAgreed = settings.getBoolean(KEY_DISCLAIMER_AGREED, false);

        if (!hasAgreed) {
            showDisclaimerDialog();
        } else {
            proceedToMainActivity();
        }
    }

    private void showDisclaimerDialog() {
        isDisclaimerShowing = true;
        new MaterialAlertDialogBuilder(this)
                .setTitle(R.string.disclaimer_title)
                .setMessage(R.string.disclaimer_content)
                .setCancelable(false)
                .setPositiveButton(R.string.disclaimer_agree, (dialog, which) -> {
                    // 保存用户同意状态
                    SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putBoolean(KEY_DISCLAIMER_AGREED, true);
                    editor.apply();

                    isDisclaimerShowing = false;
                    proceedToMainActivity();
                })
                .setNegativeButton(R.string.disclaimer_exit, (dialog, which) -> {
                    isDisclaimerShowing = false;
                    finish();
                })
                .show();
    }

    private void proceedToMainActivity() {
        new Handler().postDelayed(() -> {
            if (!isFinishing() && !isDisclaimerShowing) {
                startActivity(MainActivity.class);
                finish();
            }
        }, 800);
    }

    @Override
    public void onBackPressed() {
        // 如果正在显示免责声明，禁用返回键
        if (!isDisclaimerShowing) {
            super.onBackPressed();
        }
    }
}